package com.gxa.zhonglong.service.impl;

import com.gxa.zhonglong.common.ExceptionCode;
import com.gxa.zhonglong.exception.BusinessException;
import com.gxa.zhonglong.mapper.CodeMapper;
import com.gxa.zhonglong.pojo.Code;
import com.gxa.zhonglong.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : 宸濯
 * Date: 2021/10/27 15:57
 * Description:
 * Version: V1.0
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeMapper codeMapper;

    @Override
    public List<Map<String, Object>> selectAll() throws BusinessException {
        final List<Map<String, Object>> maps = codeMapper.selectAll();
        if(maps.size()==0){
            throw new BusinessException(ExceptionCode.NODATA);
        }
        return maps;
    }

    @Override
    public String generation(Long id) {
        final Map<String, Object> maps = codeMapper.selectById(id);
        final StringBuilder stringBuilder = new StringBuilder(maps.get("prefix").toString());
        Date date = null;
        SimpleDateFormat simpleDateFormat=null;
        //中间是否添加日期
        if ((Boolean) maps.get("isDate")){
            date=new Date();
            simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            stringBuilder.append(simpleDateFormat.format(date));
        }
        //中间是否添加时间
        if ((Boolean) maps.get("isTime")){
            date=new Date();
            simpleDateFormat = new SimpleDateFormat("HHmmss");
            stringBuilder.append(simpleDateFormat.format(date));
        }
        //添加流水号
        final Long startNum = (Long)maps.get("startNum")+1;
        for(int i=0;i<Integer.parseInt(maps.get("serial").toString())-startNum.toString().length();i++){
            stringBuilder.append(0);
        }
        //修改流水号起始数
        final Code code = new Code();
        code.setStartNum(startNum);
        code.setId((Long)maps.get("id"));
        codeMapper.update(code);
        //添加流水号起始数
        stringBuilder.append(startNum);
        return stringBuilder.toString();
    }

    @Override
    public void add(Code code) throws BusinessException {
        if (!codeMapper.add(code)){
            throw new BusinessException(ExceptionCode.ADD_DEFEATED);
        }
    }

    @Override
    public void update(Code code) throws BusinessException {
        if (!codeMapper.update(code)){
            throw new BusinessException(ExceptionCode.UPDATE_FALSE);
        }
    }

    @Override
    public void del(Long id) throws BusinessException {
        if (!codeMapper.del(id)){
            throw new BusinessException(ExceptionCode.DELETE_FALSE);
        }
    }
}
